const fs = require('fs')
const pkg = require('ssh2')
const {
	Client
} = pkg;
module.exports = function(
	filePath,
	uploadServeData,
	isH5 = false,
	isCover = true
) {
	const {
		dir: uploadPath,
		ip: serverIP,
		root: serverUsername,
		pwd: serverPassword,
	} = uploadServeData
	return new Promise((resolve, reject) => {
		if (!filePath) return reject('filePath not empty!!')
		if (!serverIP) return reject('serverIP not empty!!')
		if (!serverUsername) return reject('serverUsername not empty!!')
		if (!serverPassword) return reject('serverPassword not empty!!')
		const pathName = filePath.split('/')[filePath.split('/').length - 1]
		const conn = new Client();
		conn.on('ready', () => {
			conn.sftp(async (error, sftp) => {
				if (error) {
					conn.end();
					return reject(`Error establishing SFTP connection: ${error}`)
				}

				if(isH5) {
					copyDirectoryRecursive(filePath, uploadPath, sftp);
					resolve()
				} else {
					const remotePath = uploadPath[uploadPath.length - 1] === '/' ?
						uploadPath + pathName : uploadPath + '/' + pathName;
					const readStream = fs.createReadStream(filePath);
					sftp.exists(remotePath, isExists => {
						if (isExists && !isCover) return reject('文件已存在')
						const writeStream = sftp.createWriteStream(remotePath);
						writeStream.on('close', () => {
							conn.end();
							resolve()
						});
						readStream.pipe(writeStream);
					})
				}
			});
		});

		conn.on('error', (error) => {
			reject('服务器连接失败')
			throw new Error('服务器连接失败', error)
		});

		conn.connect({
			host: serverIP,
			port: 22,
			username: serverUsername,
			password: serverPassword,
			readyTimeout: 60 * 1000
		});
	})

}

function copyDirectoryRecursive(sourceDir, targetDir, sftp) {
	fs.readdirSync(sourceDir).forEach(file => {
		const sourceFile = `${sourceDir}/${file}`;
		const targetFile = `${targetDir}/${file}`;
		if (fs.statSync(sourceFile).isDirectory()) {
			sftp.mkdir(targetFile, error => {
				copyDirectoryRecursive(sourceFile, targetFile, sftp);
			});
		} else {
			sftp.fastPut(sourceFile, targetFile);
		}
	});
}